package cn.com.acca.ma.mybatis.util;

import java.io.IOException; 
import java.io.Reader;

import java.sql.SQLException;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory; 
import org.apache.ibatis.session.SqlSessionFactoryBuilder; 
  
public class MyBatisUtil  { 
    private  final static SqlSessionFactory sqlSessionFactory; 
    static { 
       String resource = "mybatis-config.xml"; 
       Reader reader = null; 
       try { 
           reader = Resources.getResourceAsReader(resource); 
       } catch (IOException e) { 
           System.out.println(e.getMessage()); 
           
       } 
       sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader); 
    }
    
    public static SqlSession openSqlSession(){
    	return sqlSessionFactory.openSession();
    }
    
    public static void closeSession(SqlSession sqlSession){
    	if(null!=sqlSession){
    		sqlSession.close();
    	}
    }

    /**
     * 先创建一个新的SqlSessionFactory，再创建一个新的SqlSession
     * @return
     */
    public static SqlSession newSqlSession(){
        String resource = "mybatis-config.xml";
        Reader reader = null;
        try {
            reader = Resources.getResourceAsReader(resource);
        } catch (IOException e) {
            System.out.println(e.getMessage());

        }
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        return sqlSessionFactory.openSession();
    }

    /**
     * 关闭SqlSessionFactory
      * @param sqlSession
     */
    public static void closeNewSqlSessionFactory(SqlSession sqlSession){
        try {
            sqlSession.getConnection().commit();
            sqlSession.getConnection().close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
